﻿using HXDNB.DAL;
using HXDNB.Infrastructure.Helper;
using System;
using System.Linq;
using System.Web.Mvc;

namespace HXDNB.CMS.Controllers
{
    public class HomeController : Controller
    {
        //首页
        public ActionResult Index()
        {
            if (Session.Keys.Count == 0)
            {
                Response.Redirect("/Home/Login");
            }
            //首页默认ID为1
            ViewBag.PageInfo = new UserBLL().GetPage(1);
            //判断用户密码是否为初始密码
            UserInfo info = new UserBLL().Get(Convert.ToInt32(Session["UserID"]));
            ViewBag.Pwd = DESEncrypt.Encrypt("123456") == info.Pwd;
            //
            return View();
        }
        //登录
        public ActionResult Login()
        {
            Session.Clear();
            return View();
        }
        //登录
        [HttpPost]
        public ActionResult Login(string Name, string Pwd)
        {
            if (string.IsNullOrWhiteSpace(Name) == false)
            {

                UserBLL BLl = new UserBLL();
                UserInfo Info = BLl.GetList(Name).FirstOrDefault();
                if (Info == null || Info.Id == 0)
                {
                    ViewBag.result = -1;//用户名找不到
                }
                else
                {
                    string DPwd = DESEncrypt.Encrypt(Pwd);
                    if (DPwd != Info.Pwd)
                    {
                        ViewBag.result = -2;//密码错误
                    }
                    else
                    {
                        BaseController Base = new BaseController();
                        Session["UserID"] = Info.Id;
                        Session["UserName"] = Info.Name;
                        Session["Role"] = Info.Role;
                        Session["RoleName"] = new UserBLL().GetRoles()[Info.Role];
                        Session["MeunRole"] = Info.MeunRole;
                        return RedirectToAction("Index", "Home");
                    }
                }
            }
            else
            {
                ViewBag.result = -3;//用户名为空
            }
            return View();
        }
        //上传图片
        [HttpPost]
        public string UpImg()
        {
            string filename = Upload.UpLoadImg("filedata");
            string result = "{\"err\":\"" + (filename == null ? "上传失败" : "") + "\",\"msg\":\"img/" + filename + "\"}";
            return result;
        }
        //上传图片
        [HttpPost]
        public string UpImgAD()
        {
            string filename = Upload.UpLoadImg("filedata", "~/Upload/Ad/");
            string result = "{\"err\":\"" + (filename == null ? "上传失败" : "") + "\",\"msg\":\"img/" + filename + "\"}";
            return result;
        }
    }
}
